package gu.sql2java.manager;

import static com.google.common.base.Strings.isNullOrEmpty;
import static gu.sql2java.manager.parser.ParserSupport.parseSelectUnchecked;

import gu.sql2java.pagehelper.Page;
import gu.sql2java.pagehelper.PageHelper;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.statement.select.Limit;
import net.sf.jsqlparser.statement.select.Offset;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

class PageQueryLimitOffsetImpl implements IPageQueryWrap {

	public PageQueryLimitOffsetImpl() {
	}

	@Override
	public String wrap(String sql, int startRow, int numRows) {
		Select select;
		if(!isNullOrEmpty(sql) && null != (select = parseSelectUnchecked(sql))){
			/**
			 * 提供startRow,numRows的情况下优先使用startRow,numRows
			 * 没有提供startRow,numRows的情况下,检查是否PageHelper是否启动,
			 * 如果启动,则使用PageHelper提供的参数来计算分页查询的起始偏移(offset)和记录数量(row_count)
			 */
			boolean rebuild = true;
			if(startRow == 1 && numRows < 0){
				@SuppressWarnings("rawtypes")
				Page page;
				if(null != (page = PageHelper.getLocalPage()) && page.isEnable()){
					startRow = (page.getPageNum() - 1 ) * page.getPageSize();
					numRows = page.getPageSize();
				}else{
					rebuild = false;
				}
			}else {
				startRow --;
			}
			if(rebuild){
				PlainSelect plainSelect = (PlainSelect)select.getSelectBody();
				if(numRows > 0){
					Limit limit = new Limit();
					limit.setRowCount(new LongValue(numRows));
					plainSelect.setLimit(limit);
				}
				if(startRow >= 0){
					Offset offset = new Offset();
//					offset.setOffset(startRow);
					// update for jsqlparser 4.5
					offset.setOffset(new LongValue(startRow));
					plainSelect.setOffset(offset);
				}
				return select.toString();
			}
		}
		return null;
	}

}
